<?php

declare(strict_types=1);

namespace App\Kernel\Log;

use Hyperf\Context\Context;
use Hyperf\Coroutine\Coroutine;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;

/**
 * https://hyperf.wiki/3.1/#/zh-cn/logger?id=%e7%bb%9f%e4%b8%80%e8%af%b7%e6%b1%82%e7%ba%a7%e5%88%ab%e6%97%a5%e5%bf%97
 */
class AppendRequestIdProcessor implements ProcessorInterface
{
    public const REQUEST_ID = 'log.request.id';

    public function __invoke(array|LogRecord $record): array|LogRecord
    {
        $record['extra']['request_id'] = Context::getOrSet(self::REQUEST_ID, uniqid());
        $record['extra']['coroutine_id'] = Coroutine::id();
        return $record;
    }
}
